package com.newtouch.cq.base.starter.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newtouch.cq.base.starter.business.entity.SysUserRole;
import com.newtouch.cq.base.starter.business.mapper.BaseSysUserRoleMapper;
import com.newtouch.cq.base.starter.business.model.dto.SysUserRoleDTO;
import com.newtouch.cq.base.starter.business.service.IBaseSysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户和角色的关系表 服务实现类
 * </p>
 *
 * @author Alex
 * @since 2021-08-02
 */
@Service
public class BaseSysUserRoleServiceImpl extends ServiceImpl<BaseSysUserRoleMapper, SysUserRole> implements IBaseSysUserRoleService {

    @Override
    @Transactional
    public void deleteByUserIdAndSave(SysUserRoleDTO dto) {
        deleteByUserId(dto.getUserId());

        List<SysUserRole> userRoles = CollUtil.newArrayList();
        dto.getRoleIds().stream().forEach(roleId -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(dto.getUserId());
            userRole.setRoleId(roleId);
            userRoles.add(userRole);
        });

        this.saveBatch(userRoles);
    }

    @Override
    public List<SysUserRole> getAllByUserId(long userId) {
        LambdaQueryWrapper<SysUserRole> wrapper = Wrappers.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getUserId, userId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<SysUserRole> getAllByRoleId(long roleId) {
        LambdaQueryWrapper<SysUserRole> wrapper = Wrappers.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getRoleId, roleId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public boolean userHasRole(long userId, long roleId) {
        LambdaQueryWrapper<SysUserRole> wrapper = Wrappers.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getUserId, userId).eq(SysUserRole::getRoleId, roleId);
        return baseMapper.selectCount(wrapper) > 0;
    }

    @Override
    public void deleteByRoleId(long roleId) {
        Map<String, Object> map = MapUtil.newHashMap();
        map.put("role_id", roleId);
        baseMapper.deleteByMap(map);
    }

    @Override
    public void deleteByUserId(long userId) {
        Map<String, Object> map = MapUtil.newHashMap();
        map.put("user_id", userId);
        baseMapper.deleteByMap(map);
    }
}
